<?php
namespace Lib;

use Config\Redis as RedisConfig;
use Exception;
use Redis as RedisClient;

/**
 * redis库类.
 */
class Redis
{
    /**
     * 实例数组.
     *
     * @var array
     */
    protected static $instance = [];

    /**
     * 获取实例.
     * @param $config_name
     * @throws \Exception
     * @return mixed
     */
    public static function instance($config_name)
    {
        if (!isset(RedisConfig::${$config_name})) {
            echo "\\Config\\Redis::{$config_name} not set\n";

            throw new Exception("\\Config\\Redis::{$config_name} not set\n");
        }

        if (empty(self::$instance[$config_name])) {
            $config = RedisConfig::${$config_name};
            $host = $config['host'];
            $port = $config['port'] ? $config['port'] : 6379;
            $redis = new RedisClient();
            if (!$redis->pconnect($host, $port)) {
                echo "redis connect error \n";

                throw new Exception("redis connect error \n");
            }
            if (isset($config['password'])) {
                $redis->auth($config['password']);
            }
            if (isset($config['database'])) {
                $redis->select($config['database']);
            }
            self::$instance[$config_name] = $redis;
        }

        return self::$instance[$config_name];
    }

    /**
     * 关闭redis库实例.
     *
     * @param string $config_name
     */
    public static function close($config_name): void
    {
        if (isset(self::$instance[$config_name])) {
            self::$instance[$config_name]->close();
            unset(self::$instance[$config_name]);
            self::$instance[$config_name] = null;
        }
    }

    /**
     * 关闭所有redis库实例.
     */
    public static function closeAll(): void
    {
        foreach (self::$instance as $connection) {
            $connection->close();
        }
        self::$instance = [];
    }
}
